<?php

namespace app\queue\yunjin;

use app\common\model\haikang\HkConsumerMsg;
use app\common\model\haikang\HkConsumerMsgWeek;
use app\common\model\QueueErrorLog;
use app\common\model\work_area\HkDeviceSerial;
use app\common\model\work_area\WorkAreaStandVoice;
use app\common\model\yunjin\YjMsgCorr;
use app\common\service\broadcast\IpBroadcastService;
use think\facade\Db;
use think\queue\Job;

class MsgCallbackQueue
{
    /**
     * fire方法是消息队列默认调用的方法
     * @param Job $job 当前的任务对象
     * @param array|mixed $data 发布任务时自定义的数据
     */
    public function fire(Job $job, $data)
    {
        $isJobDone = $this->doJob($data);
        if ($isJobDone) {
            // 如果任务执行成功， 记得删除任务
            $job->delete();
        } else {
            /** 如果大于2次则删除该任务 */
            if ($job->attempts() > 2) {
                $job->delete();
            } else {
                $job->release(2); //$delay为延迟时间，表示该任务延迟2秒后再执行
            }
        }
    }


    /**
     * 处理队列消息
     */
    private function doJob($param)
    {
        try {
            //语音文件服务器域名
            $file_domain = 'https://aiscreen.smartrail.cloud/';
            //查询摄像头
            $hk_device_serial = HkDeviceSerial::where(['yj_name' => $param['cameraName']])->field(['id', 'name', 'channel_no', 'device_serial', 'work_area_stand_id', 'device_rod_id'])->find();
            //查询海康语音记录
            $yj_msg_corr = YjMsgCorr::where(['yj_msg' => $param['algorithmName']])->find();
            //添加抓拍信息
            if (!empty($hk_device_serial) && !empty($yj_msg_corr)) {
                //文件上传地址
                $url = "https://oss.smartrail.cloud/upload/file_upload/imgUpload";
                $res = http_post($url, ['srcPicData' => $param['alarmPicData']]);
                if ($res) {
                    $imagePath = json_decode($res, true);
                    $data = [
                        'platform_type' => 2,
                        'msg_type' => 'ai_message_task_result',
                        'msg_id' => $param['dataID'],
                        'yj_data_id' => $param['dataID'],
                        'msg_name' => $yj_msg_corr->hk_msg,
                        'timestamp' => $param['timestamp'],
                        'channel_no' => $hk_device_serial->channel_no,
                        'device_serial' => $hk_device_serial->device_serial,
                        'date_time' => $param['timestamp'],
                        'image_url' => $imagePath['data']['directory'],
                        'server_img_url' => $imagePath['data']['directory'],
                        'work_area_stand_id' => $hk_device_serial->work_area_stand_id,
                        'device_name' => $param['cameraName'],
                        'device_rod_id' => $hk_device_serial->device_rod_id
                    ];
                    HkConsumerMsg::create($data);
                    HkConsumerMsgWeek::create($data);
                    $voice_file = WorkAreaStandVoice::where(['hk_device_serial_id' => $hk_device_serial->id, 'event_type' => $yj_msg_corr->hk_msg])
                        ->order("id DESC")
                        ->cache(60)
                        ->value('file');
                    $time = time();
                    //每天6点到晚上21点播放
                    $startTimeStamp = strtotime(date('Y-m-d 6:00:00'));
                    $endTimeStamp = strtotime(date('Y-m-d 21:00:00'));
                    if (!empty($voice_file) && $time >= $startTimeStamp && $time <= $endTimeStamp) {
                        //远程调用ip广播
                        IpBroadcastService::speech([
                            'url' => $file_domain . $voice_file,
                            'hk_device_serial_id' => $hk_device_serial->id
                        ]);
                    }
                    unset($voice_file);
                }
            }
            unset($hk_device_serial);
            unset($yj_msg_corr);
        } catch (\Exception $e) {
            // 验证失败
            $this->fail($param, $e->getMessage());
        }
        return true;
    }

    /**
     * 队列失败记录
     * @param $data
     * @param $remarks
     * @return void
     */
    private function fail($data, $remarks = '')
    {
        QueueErrorLog::create([
            'queue_name' => 'MsgCallbackQueue',
            'queue_data' => json_encode($data),
            'remarks' => $remarks
        ]);
    }
}